Page({
  data: {
    latitude: 23.099994,
    longitude: 113.324520,
    markers: [{
      iconPath: "/images/Vector-Location-PNG-Free-Download.png",
      id: 0,
      latitude: 23.099994,
      longitude: 113.324520,
      width: 50,
      height: 50
    }],
    searchQuery: ''
  },

  onLoad: function() {
    // 初始化时获取用户位置
    this.getUserLocation();
  },

  getUserLocation: function() {
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        const { latitude, longitude } = res;
        this.setData({
          latitude,
          longitude,
          markers: [{
            iconPath: "/images/Vector-Location-PNG-Free-Download.png",
            id: 0,
            latitude: latitude,
            longitude: longitude,
            width: 50,
            height: 50
          }]
        });
      }
    });
  },

  onInputChange: function(e) {
    // 监听输入框内容变化
    this.setData({
      searchQuery: e.detail.value
    });
  },

  onSearch: function() {
    // 获取用户输入的地址，并通过腾讯地图 API 获取经纬度
    const query = this.data.searchQuery.trim();
    if (query) {
      this.searchLocation(query);
    }
  },
  go: function() {
    wx.navigateTo({
        url:'/pages/map/path/path'
    })
},

  searchLocation: function(query) {
    const that = this;
    const key = '4KTBZ-4ILWB-5WJUL-JRJY3-JM2X6-6KBTD';
    wx.request({
      url: `https://apis.map.qq.com/ws/geocoder/v1/`,
      data: {
        address: query,
        key: key
      },
      success(res) {
        if (res.data.status === 0) {
          const { lat, lng } = res.data.result.location;
          that.setData({
            latitude: lat,
            longitude: lng,
            markers: [{
              iconPath: "/images/Vector-Location-PNG-Free-Download.png",
              id: 1,
              latitude: lat,
              longitude: lng,
              width: 50,
              height: 50
            }]
          });
        } else {
          wx.showToast({
            title: '未找到该地址',
            icon: 'none'
          });
        }
      },
      fail(err) {
        wx.showToast({
          title: '请求失败，请稍后再试',
          icon: 'none'
        });
      }
    });
  }
});

